package com.flyco.modules.ums.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.pms.entity.PmsProduct;
import com.flyco.modules.ums.entity.UmsMemberStaff;
import com.flyco.modules.ums.service.IUmsMemberStaffService;

import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.flyco.common.system.base.controller.BaseController;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 内部员工
 * @Author: flyco
 * @Date:   2021-02-03
 * @Version: V1.0
 */
@Slf4j
@Api(tags="内部员工")
@RestController
@RequestMapping("/f/ums/umsMemberStaff")
public class UmsMemberStaffController extends BaseController<UmsMemberStaff, IUmsMemberStaffService> {
	@Autowired
	private IUmsMemberStaffService umsMemberStaffService;

	/**
	 * 分页列表查询
	 *
	 * @param umsMemberStaff
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "内部员工-分页列表查询")
	@ApiOperation(value="内部员工-分页列表查询", notes="内部员工-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(UmsMemberStaff umsMemberStaff,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<UmsMemberStaff> queryWrapper = QueryGenerator.initQueryWrapper(umsMemberStaff, req.getParameterMap());
		Page<UmsMemberStaff> page = new Page<UmsMemberStaff>(pageNo, pageSize);
		IPage<UmsMemberStaff> pageList = umsMemberStaffService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 * 添加
	 *
	 * @param umsMemberStaff
	 * @return
	 */
	@AutoLog(value = "内部员工-添加")
	@ApiOperation(value="内部员工-添加", notes="内部员工-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody UmsMemberStaff umsMemberStaff) {
		umsMemberStaffService.save(umsMemberStaff);
		return Result.ok("添加成功！");
	}
	
	/**
	 * 编辑
	 *
	 * @param umsMemberStaff
	 * @return
	 */
	@AutoLog(value = "内部员工-编辑")
	@ApiOperation(value="内部员工-编辑", notes="内部员工-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody UmsMemberStaff umsMemberStaff) {
		umsMemberStaffService.updateById(umsMemberStaff);
		return Result.ok("编辑成功!");
	}
	
	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "内部员工-通过id删除")
	@ApiOperation(value="内部员工-通过id删除", notes="内部员工-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		umsMemberStaffService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "内部员工-批量删除")
	@ApiOperation(value="内部员工-批量删除", notes="内部员工-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.umsMemberStaffService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "内部员工-通过id查询")
	@ApiOperation(value="内部员工-通过id查询", notes="内部员工-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		UmsMemberStaff umsMemberStaff = umsMemberStaffService.getById(id);
		return Result.ok(umsMemberStaff);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param umsMemberStaff
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, UmsMemberStaff umsMemberStaff) {
      return super.exportXls(request, umsMemberStaff, UmsMemberStaff.class, "内部员工");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
	  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	  Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	  for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
		  MultipartFile file = entity.getValue();// 获取上传文件对象
		  ImportParams params = new ImportParams();
		  params.setTitleRows(2);
		  params.setHeadRows(1);
		  params.setNeedSave(true);
		  try {
			  List<UmsMemberStaff> list = ExcelImportUtil.importExcel(file.getInputStream(), UmsMemberStaff.class, params);
			  /*List<String> mobiles = list.stream().map(UmsMemberStaff::getMobile).distinct().collect(Collectors.toList());
			  if (!Objects.equals(list.size(),mobiles.size())) {
				  return Result.error("文件导入失败: 手机号有重复记录，请检查后重试");
			  }*/
			  List<UmsMemberStaff> errList = list.stream()
					  .filter(x -> oConvertUtils.isEmpty(x.getMobile()) ).collect(Collectors.toList());
			  if (errList.size() > 0) {
				  return Result.error("文件导入失败: 手机号不可空，请检查后重试");
			  }
			  List<UmsMemberStaff> distMemberStaffList = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()-> new TreeSet<>(Comparator.comparing(UmsMemberStaff::getMobile))),ArrayList::new));
			  List<String> mobiles = distMemberStaffList.stream().map(UmsMemberStaff::getMobile).distinct().collect(Collectors.toList());

			  LambdaQueryWrapper<UmsMemberStaff> staffQuery = new LambdaQueryWrapper<>();
			  staffQuery.in(UmsMemberStaff::getMobile, mobiles);
			  List<UmsMemberStaff> dbList = umsMemberStaffService.list(staffQuery);
			  List<UmsMemberStaff> updateList = new ArrayList<>();
			  if (dbList.size() > 0) {
				  Map<String, Long> dbStaffMaps = dbList.stream().collect(Collectors.toMap(UmsMemberStaff::getMobile, UmsMemberStaff::getId, (key1, key2) -> key2));
				  List<String> dbMobiles = dbList.stream().map(UmsMemberStaff::getMobile).distinct().collect(Collectors.toList());
				  updateList = distMemberStaffList.stream().filter(item -> dbMobiles.contains(item.getMobile())).collect(Collectors.toList());
				  distMemberStaffList.removeAll(updateList);
				  updateList.forEach(u->{
					  if (dbStaffMaps.containsKey(u.getMobile())) {
						  u.setId(dbStaffMaps.get(u.getMobile()));
					  }
				  });
			  }
			  //update-begin-author:taoyan date:20190528 for:批量插入数据
			  long start = System.currentTimeMillis();
			  if (updateList.size() > 0) {
				  umsMemberStaffService.updateBatchById(updateList);
			  }
			  if (distMemberStaffList.size() > 0) {
				  umsMemberStaffService.saveBatch(distMemberStaffList);
			  }
			  //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
			  //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
			  log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
			  //update-end-author:taoyan date:20190528 for:批量插入数据
			  return Result.ok("文件导入成功！新增行数：" + distMemberStaffList.size() + "，更新行数：" + updateList.size());
		  } catch (Exception e) {
			  log.error(e.getMessage(), e);
			  return Result.error("文件导入失败:" + e.getMessage());
		  } finally {
			  try {
				  file.getInputStream().close();
			  } catch (IOException e) {
				  e.printStackTrace();
			  }
		  }
	  }
	  return Result.error("文件导入失败！");
  }

}
